﻿namespace EasyToolkit.Excel.BindingTemplates
{
    using System;
    using System.Linq;
    using System.Reflection;
    using EasyToolkit.Tools.Extensions;
    using EasyToolkit.Tools.Reflection;

    static class ConstextualMethodRetriever
    {
        static public MethodInfo RetrieveContextualMethodInfo(Type mainBindingDefinitionType, string methodName)
        {
            string[] methodNameElements = methodName.Split(',');

            if (methodNameElements.Count() != 1 && methodNameElements.Count() != 3)
                throw new ArgumentException("The 'method' separator is ',' and it must be composed this way 'Assembly,Type,Method' or, if the method is part of the calling instance, 'Method'");

            Type type;
            if (methodNameElements.Count() == 1)
            {
                methodName = methodNameElements[0].EmptyIfNull().Trim();
                type = mainBindingDefinitionType;
            }
            else
            {
                methodName = methodNameElements[2].EmptyIfNull().Trim();
                type = TypeHelpers.GetType(methodNameElements[0], methodNameElements[1]);
            }

            MethodInfo methodInfo = type.GetMethod(methodName);
            if (methodInfo == null)
                throw new ArgumentException(string.Format("Method '{0}' not found", methodName));

            return methodInfo;
        }
    }
}
